package sysop

import (
	"fmt"
	"os/exec"
	"strconv"
)

// ByBind 自有程序CPU绑定获取（运行），二进制
func ByBind(proc string) (string, error) {
	cmdLine := fmt.Sprintf("cat /proc/$(pidof %s)/cmdline", proc)
	dataBytes, err := exec.Command("/bin/bash", "-c", cmdLine).Output()

	if err != nil {
		fmt.Printf("程序运行信息获取失败。err: %v\n", err)
		return "", err
	}
	start := 0
	coreFlag := false
	for i, v := range dataBytes {
		if v != 0 {
			continue
		}
		str := string(dataBytes[start:i])
		start = i + 1
		if str == "-c" {
			coreFlag = true
			continue
		}
		if !coreFlag {
			continue
		}
		intData, err := strconv.ParseInt(str, 0, 0)
		if err != nil {
			fmt.Printf("程序运行信息获取失败。err: %v\n", err)
			return "", err
		}
		binData := fmt.Sprintf("%b", intData)
		return binData, nil
	}
	return "", fmt.Errorf("无CPU绑定信息")
}
